package com.gljx.web.controller;

import com.gljx.util.*;
import com.gljx.web.Entity.*;
import com.gljx.web.dao.ChangecoachtwoMapper;
import com.gljx.web.service.ChangecoachTwoService;
import com.gljx.web.service.CustomLogService;
import com.gljx.web.service.DepartmentService;
import com.gljx.web.service.DropexerciseTwoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author lcx
 * @Date 2017/11/28 0028 上午 10:07
 * 科目二换教练
 */
@Controller
@RequestMapping("/")
public class ChangecoachTwoContraller {

    @Autowired
    ChangecoachTwoService changecoachTwoService;
    @Autowired
    DepartmentService departmentService;
    @Autowired
    CustomLogService customLogService;
    @Autowired
    ExerciseCarPlanController exerciseCarPlanController;
    @Autowired
    PersonController personController;
    @Autowired
    ChangecoachtwoMapper changecoachtwoMapper;

    /**
     * @Author lcx
     * @Date 2017/11/20 0020 上午 10:43
     * 查询科目二分车列表
     */
    @RequestMapping("/queryChangecoachTwo/look.action")
    public String queryChangecoachTwo(HttpServletRequest request, @RequestParam(value = "fnumber", defaultValue = "") String fnumber
            , @RequestParam(value = "fdescription", defaultValue = "") String fdescription
            , @RequestParam(value = "cfstudentname", defaultValue = "") String cfstudentname
            , @RequestParam(value = "beginTime", defaultValue = "") String beginTime
            , @RequestParam(value = "endTime", defaultValue = "") String endTime
            , @RequestParam(value = "state", defaultValue = "") String state
            , @RequestParam(value = "alertType", defaultValue = "") String alertType) {


        PageBean<Changecoachtwo> pb = new PageBean<>();
        //获取操作人信息
        User user = (User) request.getSession().getAttribute("user");
        try {
            fnumber = fnumber.trim();//去空格
            fdescription = fdescription.trim();
            cfstudentname = cfstudentname.trim();
            //第一次进来
            if ("first".equals(state)) {
                beginTime = TimeFormat.getMonth();
                endTime = TimeFormat.getNowTime();
                pb = getPageBean(request, user.getFcompanyid(), fnumber, fdescription, cfstudentname, beginTime, endTime, "");
            } else if ("".equals(state) && "".equals(beginTime) || "".equals(endTime)) {
                pb = getPageBean(request, user.getFcompanyid(), fnumber, fdescription, cfstudentname, beginTime, endTime, null);
            } else {
                pb = getPageBean(request, user.getFcompanyid(), fnumber, fdescription, cfstudentname, beginTime, endTime, "");
            }
            //获取当前分页的值
            List<Changecoachtwo> changecoachTwoList = pb.getBeanList();
            //把获取到的数据传回页面
            for (Changecoachtwo changecoachTwo : changecoachTwoList) {
                //查询学员信息
                changecoachTwo.setChangecoachtwoentryList(changecoachTwoService.selectChangecoachTwoentryByFid(changecoachTwo.getFid(), cfstudentname));
            }
            //合计信息总条数
            String messageAmount="共有"+pb.getTr()+"条信息";

            //返回界面的搜索条件
            request.setAttribute("messageAmount",messageAmount);
            request.setAttribute("fnumber", fnumber);
            request.setAttribute("fdescription", fdescription);
            request.setAttribute("cfstudentname", cfstudentname);
            request.setAttribute("beginTime", beginTime);
            request.setAttribute("endTime", endTime);

            request.setAttribute("changecoachTwoList", changecoachTwoList);
            request.setAttribute("pb", pb);
            request.setAttribute("alertType", alertType);

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return "/backHome/practiseCAR/ChangecoachTwo/ChangecoachTwoList";
    }

    public PageBean<Changecoachtwo> getPageBean(HttpServletRequest request, String companyId, String fnumber,
                                                String fdescription, String cfstudentname,
                                                String beginTime, String endTime,
                                                String state) throws Exception {

        int offset;//从第几条数据开始加载
        if (request.getParameter("pager.offset") == null) {
            offset = 0;
        } else {
            offset = Integer.parseInt(request.getParameter("pager.offset"));
        }
        //拼接SQL语句
        StringBuffer psql = new StringBuffer();
        if (state == null) {
            psql.append("SELECT DISTINCT" +
                    "   c.fid," +
                    "  c.FNUMBER, " +
                    "  TO_CHAR(c.FBIZDATE, 'YYYY-MM-DD') FBIZDATE, " +
                    "  c.FDESCRIPTION, " +
                    "  u.NAME                            checkName, " +
                    "  u1.NAME                           createName," +
                    "   c.CFBILLSTATE, " +
                    "   e.FNAME_L2 cflcsjidName," +
                    "   c.FCREATETIME," +
                    "   TO_CHAR(c.FBIZDATE, 'YYYY-MM-DD') " +
                    " FROM " +
                    "  CT_DS_CHANGECOACHTWO c LEFT JOIN T_E_USER U ON c.FAUDITORID = u.FID " +
                    "  LEFT JOIN T_E_USER u1 ON c.FCREATORID = u1.FID " +
                    "  LEFT JOIN ct_ds_exercisecarplan e ON c.CFLCSJID = e.fid" +
                    "  LEFT JOIN CT_DS_CHANGECOACHTWOENTRY c2 on c.fid = c2.FPARENTID" +
                    "  LEFT JOIN CT_DS_STUDENT S ON c2.CFSTUDENTID = S.FID" +
                    " where c.FCONTROLUNITID= '" + companyId + "'");
            if (!"".equals(fnumber)) {
                psql.append(" and c.FNUMBER LIKE '%" + fnumber + "%' ");
            }
            if (!"".equals(fdescription)) {
                psql.append(" and c.FDESCRIPTION LIKE '%" + fdescription + "%' ");
            }
            if (!"".equals(cfstudentname)) {
                psql.append(" and S.FNAME_L2 LIKE '%" + cfstudentname + "%' ");
            }
            psql.append(" ORDER BY c.FCREATETIME DESC");
        } else {
            psql.append("SELECT DISTINCT" +
                    "   c.fid," +
                    "  c.FNUMBER, " +
                    "  TO_CHAR(c.FBIZDATE, 'YYYY-MM-DD') FBIZDATE, " +
                    "  c.FDESCRIPTION, " +
                    "  u.NAME                            checkName, " +
                    "  u1.NAME                           createName," +
                    "   c.CFBILLSTATE, " +
                    "   e.FNAME_L2 cflcsjidName," +
                    "   c.FCREATETIME," +
                    "   TO_CHAR(c.FBIZDATE, 'YYYY-MM-DD') " +
                    " FROM " +
                    "  CT_DS_CHANGECOACHTWO c LEFT JOIN T_E_USER U ON c.FAUDITORID = u.FID " +
                    "  LEFT JOIN T_E_USER u1 ON c.FCREATORID = u1.FID " +
                    "  LEFT JOIN ct_ds_exercisecarplan e ON c.CFLCSJID = e.fid" +
                    "  LEFT JOIN CT_DS_CHANGECOACHTWOENTRY c2 on c.fid = c2.FPARENTID" +
                    "  LEFT JOIN CT_DS_STUDENT S ON c2.CFSTUDENTID = S.FID" +
                    " where c.FCONTROLUNITID= '" + companyId + "'");
            if (!"".equals(fnumber)) {
                psql.append(" and c.FNUMBER LIKE '%" + fnumber + "%' ");
            }
            if (!"".equals(fdescription)) {
                psql.append(" and c.FDESCRIPTION LIKE '%" + fdescription + "%' ");
            }
            if (!"".equals(cfstudentname)) {
                psql.append(" and S.FNAME_L2 LIKE '%" + cfstudentname + "%' ");
            }
            psql.append(" and  (c.FBIZDATE BETWEEN to_date('" + beginTime + "', 'YYYY/MM/DD') AND to_date('" + endTime + "', 'YYYY/MM/DD')) " +
                    "ORDER BY c.FCREATETIME DESC");
        }

        int psize = 100; //每页显示数
        int pindex = offset / psize;//+1  页码从0开始
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap = changecoachTwoService.selectPage(pindex, psql.toString(), psize);
        PageBean<Changecoachtwo> pb = new PageBean<>();
        pb.setPc(pindex); //页码
        Map<String, Object> paramMapCount = getPageBeanCount(psql.toString()); //取记录总数
        pb.setTr((int) paramMapCount.get("Pcount")); //记录总数
        pb.setPs(psize);
        pb.setBeanList((List<Changecoachtwo>) paramMap.get("v_cur")); //每页数据集
        return pb;
    }

    /**
     * 取记录总数 dmz 20160921
     *
     * @param psql SQL语句
     * @return Map
     * @throws Exception
     */
    public Map<String, Object> getPageBeanCount(String psql) throws Exception {

        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap = changecoachTwoService.selectPageCount(psql);
        return paramMap;
    }

    /**
     * @Author lcx
     * @Date 2017/11/28 0028 上午 11:26
     * 添加换教练
     */
    @RequestMapping(value = "/go_add_ChangecoachTwo")
    public String goAddChangecoachTwo(HttpServletRequest request, String alertType) throws Exception {
        //获取操作人信息
        User user = (User) request.getSession().getAttribute("user");
        Department department = departmentService.queryAdminByFid(user.getFcompanyid());

        /*String number = customLogService.selectFunmber("CT_DS_CHANGECOACHTWO", user.getFcompanyid());*/
        String fnumber = GetFnumber.fnumbers("KMEHJL");

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String fbizdate = sdf.format(new Date());

        //查询练车时间
        Map map3 = exerciseCarPlanController.getExerciseCarPlan(request, "", "", "0");
        //查询教练弹窗信息
        Map map1 = personController.getPageAsJl(request, "", "", "0");

        request.setAttribute("fbizdate", fbizdate);
        request.setAttribute("createName", user.getName());
        request.setAttribute("fnumber", fnumber);
        request.setAttribute("department", department.getFnameL2());
        request.setAttribute("pb3", map3.get("pb"));
        request.setAttribute("exerciseCarPlans", map3.get("sList"));
        request.setAttribute("pb1", map1.get("pb"));
        request.setAttribute("persons", map1.get("sList"));

        request.setAttribute("alertType", alertType);


        return "/backHome/practiseCAR/ChangecoachTwo/ChangecoachTwoAdd";

    }

    /**
     * @Author lcx
     * @Date 2017/11/28 0028 下午 2:04
     * 添加
     */
    @RequestMapping(value = "/add_changecoachTwo")
    public String addChangecoachTwoReg(HttpServletRequest request, Changecoachtwo changecoachtwo, @RequestParam(defaultValue = "0") String state) {

        //获取操作人信息t
        User user = (User) request.getSession().getAttribute("user");
        //公司id
        changecoachtwo.setCfficompanyid(user.getFcompanyid());
        //控制单元id
        changecoachtwo.setFcontrolunitid(user.getFcompanyid());
        //获取当前修改时间
        String createTime = TimeFormat.timeFormat(new Date());
        //创建时间
        changecoachtwo.setFcreatetime(createTime);
        //创建人id
        changecoachtwo.setFcreatorid(user.getFid());


        //获取子类
        String[] cfstudentid = request.getParameterValues("cfstudentid");//学生id
        String[] cfstudentno = request.getParameterValues("cfstudentno");
        String[] cfmobile = request.getParameterValues("cfmobile");
        String[] cfphone = request.getParameterValues("cfphone");
        String[] cfcoachid2 = request.getParameterValues("cfcoachid2");//原教练id
        String[] cfcoachid = request.getParameterValues("cfcoachid");//现在教练id
        String[] cfcoachno = request.getParameterValues("cfcoachno");//现在教练编号
        String[] cfremark = request.getParameterValues("cfremark");

        changecoachTwoService.addChangecoachTwo(changecoachtwo, cfstudentid, cfstudentno,
                cfmobile, cfphone, cfcoachid2, cfcoachid, cfcoachno, cfremark, state);


        //添加日志
        customLogService.addLog("练车管理", TimeFormat.timeFormat(new Date()) + "对科目二换教练新增", null, user.getFid());


        return "redirect:/DrivingSys/go_add_ChangecoachTwo?alertType=bc";
    }


    @RequestMapping(value = "go_update_changecoachTwo")
    public String goUpdateShareCarTwoReg(HttpServletRequest request, String fid, String xqid) throws Exception {

        //获取操作人信息
        User user = (User) request.getSession().getAttribute("user");
        Department department = departmentService.queryAdminByFid(user.getFcompanyid());

        //查询科目二分车信息
        Changecoachtwo changecoachTwoList = changecoachTwoService.selectChangecoachTwoByFid(fid);

        if (changecoachTwoList == null) {
            return "/error/not_data";
        }
        //查询练车时间
        Map map3 = exerciseCarPlanController.getExerciseCarPlan(request, "", "", "0");
        //查询教练弹窗信息
        Map map1 = personController.getPageAsJl(request, "", "", "0");

        //查询是否是经办人
        Axamine axamine = new Axamine();
        request.setAttribute("AuditState", axamine.selectAuditPerson(changecoachTwoList.getFnumber()));

        request.setAttribute("changecoachTwoList", changecoachTwoList);
        request.setAttribute("department", department.getFnameL2());
        request.setAttribute("pb3", map3.get("pb"));
        request.setAttribute("exerciseCarPlans", map3.get("sList"));
        request.setAttribute("pb1", map1.get("pb"));
        request.setAttribute("persons", map1.get("sList"));

        return "/backHome/practiseCAR/ChangecoachTwo/updateChangecoachTwo";
    }

    /**
     * @Author lcx
     * @Date 2017/11/28 0028 下午 3:53
     * 更新
     */
    @RequestMapping(value = "/update_changecoachTwo")
    public String updateRecordin(HttpServletRequest request, Changecoachtwo changecoachtwo) {

        //获取操作人信息
        User user = (User) request.getSession().getAttribute("user");

        //获取当前修改时间
        String createTime = TimeFormat.timeFormat(new Date());
        //修改时间
        changecoachtwo.setFlastupdatetime(createTime);
        //修改人id
        changecoachtwo.setFlastupdateuserid(user.getFid());

        addChangecoachTwoReg(request, changecoachtwo, "1");

        return "redirect:/DrivingSys/queryChangecoachTwo/look.action?state=first&alertType=qd";
    }

    /**
     * @Author lcx
     * @Date 2017/11/29 0029 下午 3:26
     * 删除
     */
    @RequestMapping(value = "delete_changecoachTwo")
    public String deleteChangecoachTwo(HttpServletRequest request, String[] deleteId, String[] fnumber) throws Exception {

        User user = (User) request.getSession().getAttribute("user");

        changecoachTwoService.deleteByChangecoachTwoKey(deleteId, fnumber);
        //添加日志
        customLogService.addLog("练车管理", TimeFormat.timeFormat(new Date()) + "对科目二换教练进行删除", null, user.getFid());


        return "redirect:/DrivingSys/queryChangecoachTwo/look.action?state=first";
    }

    /**
     * @Author lcx
     * @Date 2018/2/6 0005 上午 10:20
     * 科目二换教练
     */
    @RequestMapping(value = "/queryChangecoachTwoExamine")
    @ResponseBody
    public ServerResponse examine(HttpServletRequest request, @RequestParam(defaultValue = "", value = "fid") String fid,
                                  @RequestParam(defaultValue = "", value = "state") String state,
                                  @RequestParam(defaultValue = "", value = "agreed") String agreed,
                                  @RequestParam(defaultValue = "", value = "auditcomment") String auditcomment,
                                  @RequestParam(defaultValue = "", value = "fnumber") String fnumber) {

        Changecoachtwo changecoachtwo = new Changecoachtwo();

        changecoachtwo.setFid(fid);
        changecoachtwo.setFnumber(fnumber);

        return changecoachTwoService.examine(changecoachtwo, state, agreed, auditcomment);
    }

    /**
     * @Author lcx
     * @Date 2018/2/27 0027 上午 11:49
     * 提交
     */
    @RequestMapping(value = "/queryChangecoachTwoSubmit")
    @ResponseBody
    public ServerResponse submit(HttpServletRequest request,
                                 @RequestParam(defaultValue = "", value = "fnumber") String fnumber,
                                 @RequestParam(defaultValue = "", value = "fid") String fid) {
        Axamine axamine = new Axamine();
        Changecoachtwo changecoachtwo = new Changecoachtwo();

        changecoachtwo.setFid(fid);
        /*changecoachtwo.setFauditorid(((User) request.getSession().getAttribute("user")).getFid());*/
        changecoachtwo.setCfbillstate(Long.valueOf("4"));
        changecoachtwoMapper.updateByPrimaryKeySelective(changecoachtwo);
        return axamine.submissionProcess(String.valueOf(fnumber));
    }

    @RequestMapping("/queryChangecoachTwoRegXls")
    public String queryChangecoachTwoRegXls(HttpServletRequest request, HttpServletResponse response,
                                            @RequestParam(defaultValue = "", value = "fnumber") String fnumber,
                                            @RequestParam(defaultValue = "", value = "fdescription") String fdescription,
                                            @RequestParam(defaultValue = "", value = "cfstudentname") String cfstudentname,
                                            @RequestParam(defaultValue = "", value = "beginTime") String beginTime,
                                            @RequestParam(defaultValue = "", value = "endTime") String endTime) {

        //获取操作人信息
        User user = (User) request.getSession().getAttribute("user");

        //头部数据
        List<Object> data = new ArrayList<>();
        String head[] = {"单据编号", "业务日期", "参考消息", "审核人名称", "制单人名称", "单据状态", "练车时间", "学员", "学员编号", "手机",
                "电话", "教练", "教练编码", "备注", "当前教练"
        };
        //长度
        Integer length[] = {8500, 5000, 6000, 3000, 3000, 3000, 9000, 3000, 6000, 4000,
                4000, 3000, 3000, 6000, 3000};

        List<Changecoachtwoentry> changecoachtwoentryList = changecoachTwoService.selectChangecoachTworegAsXls(fnumber, fdescription, cfstudentname, beginTime, endTime, user.getFcompanyid());


        for (Changecoachtwoentry changecoachtwoentry : changecoachtwoentryList) {
            data.add(changecoachtwoentry.getFnumber());
            data.add(changecoachtwoentry.getFbizdate());
            data.add(changecoachtwoentry.getFdescription());
            data.add(changecoachtwoentry.getCheckName());
            data.add(changecoachtwoentry.getCreateName());
            data.add(stateToString.billsState(changecoachtwoentry.getCfbillstate()));
            data.add(changecoachtwoentry.getCflcsjidName());//练车时间
            data.add(changecoachtwoentry.getCfstudentName());
            data.add(changecoachtwoentry.getCfstudentno());
            data.add(changecoachtwoentry.getCfmobile());
            data.add(changecoachtwoentry.getCfphone());
            data.add(changecoachtwoentry.getCfcoachName());
            data.add(changecoachtwoentry.getCfcoachno());//教练编码
            data.add(changecoachtwoentry.getCfremark());//备注
            data.add(changecoachtwoentry.getCfcoachName2());//当前教练
        }

        try {
            //导出Excel
            CommonExport.importExcel(response, "科目二换教练" + TimeFormat.getNowTime2() + ".xls", "科目二换教练", data, head, length);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "redirect:/DrivingSys/queryChangecoachTwo/look.action?state=first";
    }

}
